package org.csu.laboratoryequipment.model;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class SeedKeySearch {
//  利用多线程进行关键词检索
    public void seedkeysearh(ArrayList<String>seedwords){
        int threadAmount = seedwords.size();
        System.out.println("启动 " + threadAmount + "个线程...");
        //用于协调多个线程的执行，它在等待计数减为零之前会阻塞线程
        CountDownLatch latch = new CountDownLatch(seedwords.size());
        long before = System.currentTimeMillis();
        for (int i = 0; i < threadAmount; i++) {
            //同时启动多个线程进行搜索,finalI变量允许在Lambda表达式中访问i的值
            int finalI = i;
            new Thread(() -> {
                //记录该线程搜索开始
                //指定分好词的搜索记录、种子关键字的搜索记录的文件路径
                List<String> dividewords;
                try {
                    dividewords = FileUtils.readLines(new File(FilePath.JIEBA_DIVIDE_WORD_FILE_NAME));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                BufferedWriter bw;
                //加载指定输出文件
                OutputStreamWriter outStream = null;
                try {
                    outStream = new OutputStreamWriter(new FileOutputStream(new File(FilePath.SEED_SEARCH_FILE_PRIFIX + "/" + seedwords.get(finalI) + ".txt")), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                bw = new BufferedWriter(outStream);
                //查询该行是否有相应的关键字，如果有将这行写入到对应的输出列表当中
                for (String s: dividewords){
                    if(StringUtils.containsIgnoreCase(s, seedwords.get(finalI)))
                    {
                        try {
                            bw.append(s);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        try {
                            bw.newLine();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                //该线程已完成
                latch.countDown();

            }).start();

        }
        try {
            //阻塞当前线程，直到 CountDownLatch 中的计数减为零,保证所有线程完成任务
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("搜索种子关键字相关的数据所用的时间是："+(end-before)+"ms");
    }
}
